package com.sdonkey.score.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.sdonkey.score.bean.UserLoginBean;
import com.sdonkey.score.dto.SystemInfo;
import com.sdonkey.score.service.IJedisService;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Date;

public class OnlineUserListener implements HttpSessionListener, HttpSessionAttributeListener, ApplicationContextAware {
    private static Logger logger = Logger.getLogger(OnlineUserListener.class);
    private static Long num = 0L;
    private IJedisService jedisService;
    private static ApplicationContext applicationContext;


    @Override
    public void sessionCreated(HttpSessionEvent event) {
        SystemInfo.startTime = new Date();
        logger.debug("系统已启动");
        logger.info("当前在线人数为:" + (num));

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) { // 退出记录
        UserLoginBean user = (UserLoginBean) event.getSession().getAttribute("user");
        if (num >= 1) {
            num--;
        }
        if (user != null) {
            logger.debug("用户 [ " + user.getName() + " ] 已退出");
        }
        try {
            jedisService = applicationContext.getBean(IJedisService.class);
            Long userCount = jedisService.getUserCount() - 1;
            if (userCount > 0 && userCount < num) {
                num = userCount;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("当前在线人数为:" + (num));
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) { // 登录记录
        if ("user".equals(event.getName())) {
            UserLoginBean user = (UserLoginBean) event.getValue();
            logger.debug("用户 [ " + user.getName() + " ] 已登录");
            num++;
            try {
                jedisService = applicationContext.getBean(IJedisService.class);
                Long userCount = jedisService.getUserCount() + 1;
                if (userCount > 0 && userCount < num) {
                    num = userCount;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("当前在线人数为:" + num);
        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        OnlineUserListener.applicationContext = applicationContext;
    }
}
